<template>
    <div class="chose-picture-container">
        <div class="container">
            <div class="row">
                <div class="col">
                    <i-input type="text" v-model="keywords" placeholder="请输入关键字"></i-input>
                </div>
                <div class="col-auto">
                    <i-button type="primary" @click="doSearch">检索</i-button>
                </div>
                <div class="col-auto">
                    <Upload
                            ref="localUpload"
                            accept=".jpg,.jpeg,.png"
                            :action="uploadAction"
                            :data="uploadFormParams"
                            :before-upload="onBeforeUpload"
                            :on-format-error="handleFormatError"
                            :on-success="uploadSuccessCallback"
                            :on-error="onError"
                            :show-file-list="false">
                        <i-button type="ghost" icon="ios-cloud-upload-outline">上传本地文件</i-button>
                    </Upload>
                </div>
            </div>
            <div class="row">
                <template v-for="item in imageList">
                    <div class="col-3 p-1 pic-div">
                        <a :key="item.path" @click="chosePicture(item.path, item.id, item.filename)">
                            <figure class="figure p-1" :id="'picture_' + item.id">
                                <img :src="imgBaseUrl + '/' + item.path" :alt="item.filename" class="figure-img img-fluid">
                                <figcaption >{{item.filename}}</figcaption>
                                <div  :class="{picActiveClass: item.id === currentId,picNoActiveClass: item.id != currentId}"></div>
                            </figure>
                        </a>
                    </div>
                </template>
            </div>
            <div class="widget-toolbox padding-10 clearfix">
                <pagination :page-count="pageMeta.last_page"
                            :total="pageMeta.total"
                            :current-page="pageMeta.current_page" @goPage="goPage"></pagination>
            </div>
        </div>
    </div>
</template>

<script>
    import AssetsApi from '../api/admin/assets'
    export default {
      data () {
        return {
          keywords: '',
          uploadHeaders: window.uploadHeaders,
          imageList: [],
          pageMeta: {
            last_page: 0,
            total: 0,
            current_page: 0
          },
          currentUrl: '',
          currentName: '',
          currentId: 0,
          query: {},
          defaultQuery: {},
          uploadFormParams: {
            'key': '', //path
            'policy': '', //OssUtilities.signature.policy
            'OSSAccessKeyId': '', //OssUtilities.signature.accessid
            'success_action_status': '200', //让服务端返回200,不然，默认会返回204
            'callback': '',//OssUtilities.signature.accessid
            'signature': '' //OssUtilities.signature.signature
          },
          uploadAction: '',
        }
      },
      created () {
        this.getAssetsList()
      },
      methods: {
        getAssetsList () {
          let self = this
          AssetsApi.getAssetsList(this.query, response => {
            self.imageList = response.data
            self.pageMeta = response.meta
          })
        },
        goPage: function (event) {
          this.query = _.assign({page: event.page}, this.defaultQuery);
          this.getAssetsList()
        },
        doSearch () {
        },
        chosePicture (url, id, name) {
          this.currentUrl = url;
          this.currentId = id;
          this.currentName = name;
          this.$emit('on-selected', {currentUrl:this.currentUrl, currentName: this.currentName, currentId: this.currentId})
        },
        uploadSuccessCallback: function (response, file) {
          //上传成功回调
          console.log(file);
          console.log(response);
          this.getAssetsList()
          // this.$emit('upload-new-image', response)
        },
        uploadFailedCallback: function (error, file) {
          //上传失败回调
          console.log(error);
          console.log(file);
        },
        handleFormatError (file) {
          this.$Notice.warning({
            title: '格式不正确',
            desc: '该文件格式不正确'
          });
        },
        /**
         *
         */
        handlePictureCardPreview (file) {
          this.dialogImageUrl = file.url
          this.dialogVisible = true
        },
        /**
         *
         */
        onError (e) {
          let self = this
          self.loading = false
          console.log(e)
        },
        /**
         *
         * @param file
         * @returns {Promise<never>}
         */
        async onBeforeUpload (file) {
          let self = this
          self.loading = true
          try {
            let [policyResponse, uploadResponse] = await Promise.all([
              AssetsApi.getAssetsPolicy(),
              AssetsApi.putAssetFile( file.name ,'cms-image')
            ])
            if (uploadResponse.data.status === true) {
              self.uploadFormParams.policy = policyResponse.data.policy
              self.uploadFormParams.OSSAccessKeyId = policyResponse.data.accessid
              self.uploadFormParams.callback = policyResponse.data.callback
              self.uploadFormParams.signature = policyResponse.data.signature
              self.uploadFormParams.key = uploadResponse.data.path
              self.uploadAction = policyResponse.data.host
            } else {
              self.loading = false
              return Promise.reject(new Error(400))
            }
          } catch (e) {
            self.loading = false
            return Promise.reject(new Error(400))
          }
        },
      },
      computed: {
        imgBaseUrl(){
          return window.Laravel.imgBaseUrl;
        }
      },
    }
</script>
<style lang="less" scoped>
    .pic-div {
        max-height: 130px;
        overflow: hidden;
        figure {
            height: 100%;
            width: 100%;
            text-align: justify;
            overflow: hidden;
            img {
                height: 85%;
                width: 100%;
                border:1px solid #ddd;
                margin-bottom: 0rem;
            }
            figcaption{
                line-height: normal;
                font-size: 90%;
                color: #868e96;
                background: #ddd;
                white-space:nowrap;
                overflow: hidden;
                text-overflow:ellipsis;
            }
            div{
                position: absolute;
                content: "\2713";
                top: 10px;
                right: 10px;
                height: 20px;
                width: 20px;
                background: rgba(0, 0, 0, 0.08);
                border:1px solid #fff;
                -webkit-border-radius: 10px;
                -moz-border-radius: 10px;
                border-radius: 10px;
                color: #fff;
                text-align: center;
                font-size: 8px;
                &:before {
                    content: "\2713";
                    font-size: 10px;
                    /*display: block;*/
                    /*position: absolute;*/
                    /*top: 10px;*/
                    right: 4.5px;
                    /*width: 20px;*/
                    /*height: 20px;*/
                    /*background: rgba(0, 0, 0, 0.08);*/
                    /*border:1px solid #fff;*/
                    /*-webkit-border-radius: 10px;*/
                    /*-moz-border-radius: 10px;*/
                    /*border-radius: 10px;*/
                    /*color: #fff;*/
                    /*text-align: center;*/
                    /*font-size: 10px;*/
                    /*z-index: 10;*/
                }
            }
        }
    }
    .picNotActiveClass{

    }
    .picActiveClass{
        color: #fff!important;
        border:1px solid #00c09e!important;
        background: #00c09e!important;
        &:after {           /*原生方式解决*/
            content: "\2713";
            display: block;
            position: absolute;
            /*top: 10px;*/
            /*right: 10px;*/
            width: 18px;
            height: 18px;
            border:1px solid #00c09e;
            -webkit-border-radius: 10px;
            -moz-border-radius: 10px;
            border-radius: 10px;
            color: #fff;
            text-align: center;
            background: #00c09e;
            font-size: 10px;
            z-index: 10;
        }
        &:before{
            content:''!important;
            border: none!important;
            background: rgba(0,0,0,0)!important;
        }
    }
</style>
